const http = require("http")
const fs = require("fs")
const qs = require("querystring");
const url = require("url")

http.createServer((req,res)=>{
    const pn = url.parse(req.url).pathname;
    // 服务器的根路由
    if(pn.includes("/api")){
        dataHandle(req,res);
    }else{
        staticHandle(req,res);
    }
}).listen(3000,()=>{
    console.log("服务器开启成功：http://localhost:3000")
})


// 处理的函数

function dataHandle(req,res){
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        programHandle(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end",()=>{
            const obj = qs.parse(str);
            programHandle(req, res, obj);
        })
    }
}

// {type:"login",xx:xx,x:xxx}
// {type:"register",xx:xx,x:xxx}
// {type:"getUser",xx:xx,x:xxx}
// {type:"getGoods",xx:xx,x:xxx}
// {type:"getBanner",xx:xx,x:xxx}

function programHandle(req, res, data){
    // 功能路由
    // 接收到数据之后，根据数据中携带的功能类型，决定执行那个具体的功能
    switch(data.type){
        case "getBanner":
            getBanner(req, res, data);
            break;
        case "login":
            login(req, res, data);
            break;
        case "register":
            register(req, res, data);
            break;
        default:
            error(req, res, data);
    }
}

function getBanner(req, res, data){
    // 服务器先读取banner数据
    fs.readFile("./database/banner.json","utf-8",(err,data)=>{
        const obj = {};
        if(err){
            obj.code = 0;
            obj.title = "数据查找失败";
            obj.data = [];
        }else{
            obj.code = 1;
            obj.title = "数据查找成功";
            obj.data = JSON.parse(data);
        }
        res.write(JSON.stringify(obj));
        res.end();
    });
}

// 失败：
//     {
//         code:0,
//         title:"数据请求失败了",
//         data:"not data"
//     }

// 成功：
//     {
//         code:1,
//         title:"恭喜，数据请求成功了",
//         data:json数据
//     }



function login(req, res, data){
    res.write("login")
    res.end();
}

function register(req, res, data){
    res.write("register")
    res.end();
}

function error(req, res, data){
    res.write("Forbidden \n You don't have permission to access this resource.");
    res.end();
}




function staticHandle(req,res){
    const pn = url.parse(req.url).pathname
    fs.readFile("./www" + pn, (err,data)=>{
        if(err){
            res.write("Forbidden \n You don't have permission to access this resource.")
        }else{
            res.write(data);
        }
        res.end();
    })
}